//
//  MainViewController.swift
//  Weibo
//
//  Created by 王武 on 2020/8/23.
//  Copyright © 2020 ww. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // 添加控制器，并不会创建 tabBar 按钮
        // 懒加载，所有的控件都会延迟创建
        addChilds()
        
        setupComposedButton()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 将添加按钮置前
        tabBar.bringSubviewToFront(composedButton)
    }
    
    // MARK: - 懒加载控件
    private lazy var composedButton: UIButton = {
        let button = UIButton()
        
        button.setImage(UIImage(named: "feed_publish"), for: .normal)
        button.setImage(UIImage(named: "feed_publish_press"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "feed_publish"), for: .normal)
        button.setBackgroundImage(UIImage(named: "feed_publish_press"), for: .highlighted)
        
        // 根据t图片大小调整尺寸
        button.sizeToFit()
        
        return button
    }()
}

// MARK: - 设置界面
extension MainViewController {
    
    // 设置添加按钮
    private func setupComposedButton() {
        // 添加按钮
        tabBar.addSubview(composedButton)
        // 调整按钮
        let count = children.count - 1
        let w = tabBar.bounds.width / CGFloat(count)
        
        composedButton.frame = tabBar.frame.insetBy(dx: 2 * w, dy: 0)
    }
    
    // 添加所有的控制器
    private func addChilds() {
        // 设置 tintColor
        tabBar.tintColor = UIColor.orange
        addChild(HomeTableViewController(), title: "首页", imageName: "home_tabbar")
        addChild(ProfileTableViewController(), title: "我的", imageName: "mine_tabbar")
        addChild(HomeTableViewController(), title: "首页", imageName: "home_tabbar")
        addChild(ProfileTableViewController(), title: "我的", imageName: "mine_tabbar")
    }
    
    // 添加控制器
    private func addChild(_ vc: UIViewController, title: String, imageName: String) {
        // 设置标题
        vc.title = title
        // 设置图像
        vc.tabBarItem.image = UIImage(named: imageName)
        
        // 导航控制器
        let nav = UINavigationController(rootViewController: vc)
        addChild(nav)
    }
}
